<template>
  <div class="body">
    <div class="form">
      <el-form
          ref="ruleFormRef"
          style="max-width: 600px; margin-bottom: 20px;"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          :size="formSize"
          status-icon
      >

        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username" class="custom-form-item">
          <el-input v-model="ruleForm.username"/>
        </el-form-item>

        <!-- 性别 -->
        <el-form-item label="性别" prop="gender" class="custom-form-item">
          <el-select v-model="ruleForm.gender" placeholder="请选择性别">
            <el-option label="男" value="1"/>
            <el-option label="女" value="0"/>
          </el-select>
        </el-form-item>

        <!-- 新密码 -->
        <el-form-item label="新密码" prop="newPassword" class="custom-form-item">
          <el-input v-model="ruleForm.newPassword" type="password" show-password/>
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item label="手机号" prop="phone" class="custom-form-item">
          <el-input 
            v-model="ruleForm.phone" 
            @input="handlePhoneInput"
            maxlength="11"
            show-word-limit
            placeholder="请输入11位手机号码"
          />
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email" class="custom-form-item">
          <el-input 
            v-model="ruleForm.email" 
            type="email"
            maxlength="50"
            show-word-limit
            placeholder="请输入邮箱地址"
          />
        </el-form-item>

        <!-- 上传头像 -->
        <el-form-item label="上传头像" prop="avatar" class="custom-form-item">
          <el-upload
              v-model:file-list="fileList"
              action="https://api.superbed.cn/upload"
              list-type="picture-card"
              :limit="1"
              :http-request="customUpload"
              :on-exceed="handleExceed"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
          >
            <el-icon>
              <Plus/>
            </el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image"/>
          </el-dialog>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item class="custom-form-item myCustom-button">
          <div class="buttonBox">
            <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import {Plus} from '@element-plus/icons-vue'
import {reactive, ref} from 'vue';
import axios from "axios";
import {useRoute} from "vue-router";
import {ElMessage} from "element-plus";
import {useUserStore} from "../stores/userStore.js";
import {User} from "../pojo/User.js";
import router from "../router/index.js";
import { el } from 'element-plus/es/locales.mjs';

const formSize = ref('default');
const route = useRoute();
const userStore = useUserStore()
const ruleFormRef = ref(null);

// 表单数据
const ruleForm = reactive({
  username: route.query.username,
  gender: route.query.gender,
  phone: route.query.phone,
  email: route.query.email,
  newPassword: null,
  avatar: null,
});

// 密码验证函数
const validatePassword = (rule, value, callback) => {
  if (!value) {
    callback();
    return;
  }
  
  const hasNumber = /\d/.test(value);
  const hasLetter = /[a-zA-Z]/.test(value);
  
  if (value.length < 6) {
    callback(new Error('密码不能少于6位'));
  } else if (!(hasNumber && hasLetter)) {
    callback(new Error('密码至少包含数字和字母两种字符'));
  } else {
    callback();
  }
};

// 手机号验证函数
const validatePhone = (rule, value, callback) => {
  if (!value) {
    callback();
    return;
  }
  
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(value)) {
    callback(new Error('请输入正确的手机号码'));
  } else {
    callback();
  }
};

// 邮箱验证函数
const validateEmail = (rule, value, callback) => {
  if (!value) {
    callback();
    return;
  }
  
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  if (!emailRegex.test(value)) {
    callback(new Error('请输入正确的邮箱地址'));
  } else if (value.length > 50) {
    callback(new Error('邮箱地址不能超过50个字符'));
  } else {
    callback();
  }
};

// 手机号输入限制函数
const handlePhoneInput = (value) => {
  // 只允许输入数字
  ruleForm.phone = value.replace(/[^\d]/g, '');
};

// 表单验证规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在2到20个字符', trigger: 'blur' }
  ],
  newPassword: [
    { validator: validatePassword, trigger: 'blur' }
  ],
  phone: [
    { validator: validatePhone, trigger: 'blur' }
  ],
  email: [
    { validator: validateEmail, trigger: 'blur' }
  ]
});


// 文件上传相关逻辑
const fileList = ref([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
}

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true;
}

const customUpload = async (option) => {
  const {file} = option;
  const newName = `custom-${Date.now()}.${file.name.split(".").pop()}`;
  const newFile = new File([file], newName, {type: file.type});

  const formData = new FormData();
  formData.append("file", newFile);
  formData.append("token", "9da11413b658494f9f6b0be149f09b9f");

  try {
    const res = await axios.post("https://api.superbed.cn/upload", formData, {
      headers: {"Content-Type": "multipart/form-data"}
    });
    ruleForm.avatar = res?.data?.url;
    ElMessage.success('头像上传成功');
  } catch (error) {
    ElMessage.error('头像上传失败');
  }
};

const handleExceed = () => {
  ElMessage.warning('最多只能上传一张头像');
};

// 表单提交
const submitForm = async (formEl) => {
  console.log('submit', formEl);
  if (!formEl) return;
  console.log('进入请求');
  await formEl.validate(async (valid) => {
    console.log('进入请22求');
    if (valid) {

      const user = new User();
      user.username = ruleForm.username;
      user.avatarUrl = ruleForm.avatar;
      user.gender = ruleForm.gender;
      user.phone = ruleForm.phone;
      user.email = ruleForm.email;
      user.userPassword = ruleForm.newPassword;

      console.log(user);

      try {
        console.log('开始请求更新用户信息');
        const res = await userStore.updateUserInfo(user);
        console.log('更新用户信息响应:', res);
        if (res.code === 200) {
          ElMessage.success({
            message: res.msg || '修改成功',
            duration: 2000,
            onClose: () => router.back()
          });
        } else if (res.code === 401) {
          ElMessage.warning(res.msg || '当前未登录账户');
          router.push('/login')
          
        
        }else{
          ElMessage.error(res.msg || '修改失败');
        }
      } catch (error) {
        console.error('更新用户信息错误:', error);
        ElMessage.error('提交失败，请稍后重试');
      }
    }
  });
};

// 表单重置
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  fileList.value = [];
  ruleForm.avatar = null;
};
</script>

<style scoped>
/* 保持原有样式不变 */
.body {
  background: linear-gradient(to bottom, #50a8fe, #f0f2f5);
  display: flex;
  justify-content: center;
}

.form {
  height: 800px;
  display: flex;
  justify-content: center;
  width: 700px;
  margin-top: 20px;
  background-color: #ffffff;
}

.custom-form-item {
  margin: 24px auto;
}

.buttonBox {
  width: 100%;
  display: flex;
  justify-content: space-around;
}

/* 上传组件样式 */
:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}
</style>